<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}参数`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="参数名" prop="csName">
        <el-input v-model="drawerProps.row!.csName" clearable></el-input>
      </el-form-item>
      <el-form-item label="参数值" prop="csValue">
        <el-input v-model="drawerProps.row!.csValue" clearable></el-input>
      </el-form-item>
      <el-form-item label="参数类型" prop="type">
        <common-select
          data-key="PARAM_TYPE"
          placeholder="请选择参数类型"
          :request-api="() => apiService.findClassify('PARAM_TYPE')"
          v-model="drawerProps.row!.type"
        ></common-select>
      </el-form-item>
      <el-form-item label="参数说明" prop="csNote">
        <el-input v-model="drawerProps.row!.csNote" clearable></el-input>
      </el-form-item>
      <el-form-item label="扩展值" prop="exValue">
        <el-input :rows="12" type="textarea" :value="JSON.stringify(drawerProps.row!.exValue)" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Params } from "@/api/types/base";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import apiService from "@/api/services/apiService";

const rules = reactive({
  csName: [{ required: true, message: "请输入参数名" }],
  csValue: [{ required: true, message: "请输入参数值" }],
  type: [{ required: true, message: "请选择参数类型" }]
});

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<Params>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
@/api/types
